package com.caunock.sqlbuilder.adapter.group.impl;

import com.caunock.sqlbuilder.adapter.group.FlexibleGroupDDLAdapter;
import com.caunock.sqlbuilder.meta.Column;
import com.caunock.sqlbuilder.meta.feature.AbstractDataType;
import com.caunock.sqlbuilder.meta.feature.ColumnType;

/**
 * MySQL适配器
 * @author Qinweitong
 */
public class MySQLAdapter extends FlexibleGroupDDLAdapter {

    @Override
    public StringBuilder type(StringBuilder builder, Column<?> column) {
        ColumnType type = column.getType();
        AbstractDataType dataType = type.getDataType();
        int length = type.getLength();
        switch (dataType) {
            case STRING:
                if (length < 65535 && length > 0) {
                    builder.append(" VARCHAR").append("(").append(length).append(")");
                } else {
                    builder.append(" TEXT");
                }
                break;
            case DECIMAL:
                int precision = type.getPrecision() == 0 ? 10 : type.getPrecision();
                int scale = type.getScale();
                builder.append(" DECIMAL(").append(precision).append(COMMA).append(scale).append(")");
                break;
            case INTEGER:
                if (length <= 2) {
                    builder.append(" TINYINT");
                } else if (length <= 4) {
                    builder.append(" SMALLINT");
                } else if (length <= 7) {
                    builder.append(" MEDIUMINT");
                } else if (length <= 9) {
                    builder.append(" INT");
                } else {
                    builder.append(" BIGINT");
                }
                break;
            case DATE:
                builder.append(" DATETIME");
                break;
            case BINARY:
                builder.append(" BLOB");
                break;
            case CONTENT:
                builder.append(" TEXT");
                break;
            default:
                break;
        }
        return builder;
    }
}
